<template>
    <div>
        <div style="height: auto;max-width: 100%">
            <div style="margin-bottom: 10px">
                <h3 class="el-icon-shopping-bag-1" style="font-style: revert">我的商品</h3>
                <el-button type="primary" style="margin-left: 40px" plain @click="Loginjudgment">添加商品</el-button>
                <el-badge style="margin-left: 10px" :value="total" class="item">
                    <el-button size="medium" @click="openmessage">消息</el-button>
                </el-badge>
            </div>
            <el-row>
                <el-col :span="8" v-for="(item, i) in numberOfElements" :key="i"
                        :offset="numberOfElements > 0 ? 0 : 0.5">
                    <el-card :body-style="{ padding: '0px' }">
                        <div class="square-img">
                            <img :src="imgurldata[i]" class="image">
                        </div>
                        <div style="padding: 14px;">
                            <h4>{{ pageTicket[i].shopname }}</h4><p style="color: red">{{ pageTicket[i].shopstate }}</p>
                            <span>￥：{{ pageTicket[i].price }}余：{{ pageTicket[i].quantity }}</span>
                            <div style="font-size: 5px">{{ pageTicket[i].timeupdate }}</div>
                            <!--                            <div class="bottomclearfix">
                                                            <el-button style="display:inline-block" type="text" :key="pageTicket[i]" class="button" @click="editbutton(pageTicket[i])">编辑</el-button>
                                                            <el-button style="display:inline-block" type="text" :key="pageTicket[i]" class="button" @click="editbutton(pageTicket[i])">上架商品</el-button>
                                                            <el-button style="display:inline-block" type="text" :key="pageTicket[i]" class="button" @click="editbutton(pageTicket[i])">删除</el-button>
                                                        </div>-->
                            <el-dropdown trigger="click">
                                <span class="el-dropdown-link">选择操作<i class="el-icon-arrow-down el-icon--right"></i></span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item @click.native="editbutton( pageTicket[i])">编辑</el-dropdown-item>
                                    <el-dropdown-item @click.native="putitemstatus( pageTicket[i].id)">上架/下架
                                    </el-dropdown-item>
                                    <el-dropdown-item @click.native="deletebutton( pageTicket[i].id)">删除
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!--        消息列表-->
        <el-dialog :visible.sync="messagelist" title="消息" width="80%" @close='flushed'>
            <div>
                <table style=" border: 1px solid #ddd;">
                    <thead>
                    <tr>
                        <th>时间</th>
                        <th>商品名称</th>
                        <th>审批结果</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(item, index) in numberOfElements" :key="index">
                        <td>{{ item.timeupdate }}</td>
                        <td>{{ item.shopname }}</td>
                        <td>{{ item.remark }}</td>
                    </tr>
                    <el-button style="margin-left: 100%" type="text" @click="flushed">确定</el-button>
                    </tbody>
                </table>
            </div>
        </el-dialog>

        <!--        添加或编辑商品-->
        <el-dialog :visible.sync="dialogVisible" title="添加或编辑商品" width="80%">
            <el-form :model="product" :rules="rules">
                <el-form-item label="商品名称" prop="shopname">
                    <el-input maxlength="15" v-model="product.shopname"></el-input>
                </el-form-item>
                <el-form-item label="商品图片" prop="shopimg">
                    <input type="file" ref="fileInput" @change="onFileChange" accept="image/jpeg">
                    <img :src="imageUrl" v-if="imageUrl" style="width: 50px">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    <input type="file" ref="fileInput" @change="onFileChange02" accept="image/jpeg">
                    <img :src="imageUrl02" v-if="imageUrl02" style="width: 50px">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    <input type="file" ref="fileInput" @change="onFileChange03" accept="image/jpeg">
                    <img :src="imageUrl03" v-if="imageUrl03" style="width: 50px">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-form-item>
                <el-form-item label="商品简介" prop="shoptext">
                    <el-input maxlength="50" v-model="product.shoptext" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="商品价格（元）" prop="price">
                    <el-input-number :min="1" v-model="product.price"></el-input-number>
                </el-form-item>
                <el-form-item label="商品数量（个）" prop="quantity">
                    <el-input-number :min="1" v-model="product.quantity"></el-input-number>
                </el-form-item>
                <el-form-item label="发货地址（寝室号等）" prop="fulladdress">
                    <el-input maxlength="25" v-model="product.fulladdress"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </div>
        </el-dialog>


        <!--        //未登录的提示框-->
        <el-dialog
                title="提示"
                :visible.sync="centerDialogVisible"
                width="70%"
                center>
            <span style="">还未进行登录！点击下方按钮前往登录</span>
            <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="FromLogin">前往登录</el-button>
  </span>
        </el-dialog>

    </div>
</template>

<script>
import {
    deleteshop,
    getshopmannge,
    postproductinformation,
    putitemstatus,
    putmessageyesorno
} from "@/views/shopmanage/shopmanage";
import $axios from "@/api/http";

export default {
    data() {
        return {
            messagelist: false,//消息不弹框展开
            numberOfElements: {},//查询到的当前页数据数
            imgurl: '',
            total: 0,  //总信息条数
            currentpage: 1,  //当前所在页默认是第一页
            pagesize: 9,  //每页显示多少行数据 默认设置为9
            ticket: [],  //这里是从后端获取的所有数据
            pageTicket: [],//分页后的当前页数据
            imgurldata: [],//存放图片的数组
            //获取当前时间
            currentDate: new Date(),
            centerDialogVisible: false,
            imageUrl: '',
            imageUrl02: '',
            imageUrl03: '',
            dialogVisible: false,
            product: {
                id: '',//商品id
                remark: '',
                shopname: '',
                shopimg: '',
                shopimg02: '',
                shopimg03: '',
                shoptext: '',
                price: null,
                quantity: null,
                fulladdress:''
            },
            rules: {
                shopname: [
                    {required: true, message: '商品名称不能为空', trigger: 'blur'},
                    { min: 1, max: 15, message: '长度在 1 到 15个字符', trigger: 'blur' }
                ],
                shopimg: [
                    {required: true, message: '请上传商品图片', trigger: 'change'}
                ],
                shoptext: [
                    {required: true, message: '商品简介不能为空', trigger: 'blur'},
                    { min: 1, max: 50, message: '长度在 1 到 50个字符', trigger: 'blur' }
                ],
                price: [
                    {required: true, message: '商品价格不能为空', trigger: 'blur'}
                ],
                fulladdress: [
                    {required: true, message: '商品地址不能为空', trigger: 'blur'},
                    { min: 1, max: 25, message: '长度在 1 到 25个字符', trigger: 'blur' }
                ],
                quantity: [
                    {required: true, message: '商品数量不能为空', trigger: 'blur'}
                ]
            }
        }
    },
    components: {},
    mounted() {
        if (window.sessionStorage.getItem("token") === null) {
            this.centerDialogVisible = true;
        }
        this.fetchProducts()
    },
    methods: {
        //返回并刷新页面
        flushed() {
            /*   setTimeout(() => {
                   // 方法区
                   //刷新页面的方法
                   location.reload()
               }, 100);*/
            this.messagelist = false
            this.total = 0
        },
        //打开消息列表
        openmessage() {
            if (window.sessionStorage.getItem("token") === null) {
                this.centerDialogVisible = true;
            } else {
                this.messagelist = true
                this.knowmessage()
            }
        },
        //点开就已读商品消息
        knowmessage() {
            putmessageyesorno(this.$store.state.user.username)
        },
        //上架or下架商品
        putitemstatus(id) {
            putitemstatus(id).then(res => {
                if (res.code === 200) {
                    this.$message({
                        message: res.msg,
                        type: 'success',
                        offset:60
                    });
                } else {
                    this.$message({
                        message: res.msg + '审核通过自动上架该商品',
                        type: 'error',
                        offset:60
                    });
                }
            })
        },
        // //下架商品
        // takedown(data){
        //
        // },
        /* shopupdate(){
             //开关商品编辑框
           this.dialogFormVisible=true
         },*/
        //删除商品
        deletebutton(id) {
            deleteshop(id).then(res => {
                if (res.code === 200) {
                    this.$message.success("删除成功！！")
                    setTimeout(() => {
                        // 方法区
                        //刷新页面的方法
                        location.reload()
                    }, 1000);
                }
            })
        },
        editbutton(id) {
            this.showDialog()
            this.product.id = id.id
            this.product.shopname = id.shopname
            // this.imageUrl = "http://192.168.10.100:8080/home/picture/" +id.shopimg
            // this.imageUrl02 = "http://192.168.10.100:8080/home/picture/" +id.shopimg02
            // this.imageUrl03 = "http://192.168.10.100:8080/home/picture/" +id.shopimg03
            this.imageUrl = "http://111.229.186.198:8080/home/picture/" +id.shopimg
            this.imageUrl02 = "http://111.229.186.198:8080/home/picture/" +id.shopimg02
            this.imageUrl03 = "http://111.229.186.198:8080/home/picture/" +id.shopimg03
            this.product.shoptext = id.shoptext
            this.product.price = id.price
            this.product.quantity = id.quantity
            this.product.fulladdress = id.fulladdress
            // console.log(this.product)
        },
        fetchProducts() {
            getshopmannge(this.$store.state.user.username).then(res => {
                // console.log(res)
                if (res.code === 200) {
                    this.numberOfElements = res.data
                    //获取当前页的数据
                    this.getPageInfo();
                    if (this.numberOfElements.length===0){
                        this.$message({
                            message: '还未添加商品!',
                            type: 'warning',
                            offset:60
                        });
                    }else {this.$message({
                        message: '数据加载成功!',
                        type: 'success',
                        offset:60
                    });}
                } else {
                    // 失败的提示
                    this.$message.error(res.succeed);
                }
            })
                .catch(function (err) {
                    console.log(err);
                })
        },
        // 获取商品的数据信息
        getPageInfo() {
            for (let i = 0; i < this.numberOfElements.length; i++) {
                //把遍历的数据添加到pageTicket里面
                if (this.numberOfElements[i].messageyesorno === 0) {
                    this.total++
                }
                this.pageTicket.push(this.numberOfElements[i]);
              // let imgurl = "http://192.168.10.100:8080/home/picture/" +this.pageTicket[i].shopimg
              let imgurl = "http://111.229.186.198:8080/home/picture/" +this.pageTicket[i].shopimg
                this.imgurldata.push(imgurl)
                //判断是否达到一页的要求
            }
        },
        // 判断是否有登录
        Loginjudgment() {
            // console.log(window.sessionStorage.getItem("token"))
            if (window.sessionStorage.getItem("token") === null) {
                this.centerDialogVisible = true;
            } else {
                //上传商品须上传手机号及微信号
                this.showDialog()
            }
        },
        //前往登录页面按钮方法
        FromLogin() {
            this.centerDialogVisible = false
            this.$router.push({
                path: 'login'
            })
        },
        //打开上传商品的弹窗
        showDialog() {
            this.dialogVisible = true;
        },
        //上传图片01
        onFileChange(event) {
            const file = event.target.files[0]
            if (file && file.type === 'image/jpeg') {
                const reader = new FileReader()
                reader.onload = (e) => {
                    if (typeof e.target.result === 'object') {
                        this.imageUrl = window.URL.createObjectURL(new Blob([e.target.result]))
                        // console.log(this.imageUrl)
                    } else {
                        this.imageUrl = e.target.result
                        // console.log(typeof this.imageUrl)
                    }
                }
                reader.readAsDataURL(file)
                this.product.shopimg = new Blob([file], {type: 'image/jpeg'})
                // console.log(file)
                console.log(this.product.shopimg)
            } else {
                this.$message.error('请选择JPEG格式的图片文件')
            }
        },  //上传图片02
        onFileChange02(event) {
            const file = event.target.files[0]
            if (file && file.type === 'image/jpeg') {
                const reader = new FileReader()
                reader.onload = (e) => {
                    if (typeof e.target.result === 'object') {
                        this.imageUrl02 = window.URL.createObjectURL(new Blob([e.target.result]))
                        // console.log(this.imageUrl)
                    } else {
                        this.imageUrl02 = e.target.result
                        // console.log(typeof this.imageUrl)
                    }
                }
                reader.readAsDataURL(file)
                this.product.shopimg02 = new Blob([file], {type: 'image/jpeg'})
                // console.log(file)
                console.log(this.product.shopimg02)
            } else {
                this.$message.error('请选择JPEG格式的图片文件')
            }
        },  //上传图片03
        onFileChange03(event) {
            const file = event.target.files[0]
            if (file && file.type === 'image/jpeg') {
                const reader = new FileReader()
                reader.onload = (e) => {
                    if (typeof e.target.result === 'object') {
                        this.imageUrl03 = window.URL.createObjectURL(new Blob([e.target.result]))
                        // console.log(this.imageUrl)
                    } else {
                        this.imageUrl03 = e.target.result
                        // console.log(typeof this.imageUrl)
                    }
                }
                reader.readAsDataURL(file)
                this.product.shopimg03 = new Blob([file], {type: 'image/jpeg'})
                // console.log(file)
                console.log(this.product.shopimg03)
            } else {
                this.$message.error('请选择JPEG格式的图片文件')
            }
        },
        beforeAvatarUpload(file) {
            console.log(file)
            console.log('beforeAvatarUpload')
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 1;
            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 1MB!');
            }
            return isJPG && isLt2M;
        },
        handleAvatarSuccess(res, file) {
            console.log('handleAvatarSuccess')
            console.log(res)
            console.log(file)
            let reader = new FileReader()
            reader.readAsDataURL(file.raw)
            reader.onload = () => {
                console.log('结果显示')
                this.imageUrl = reader.result
            }
        },
        // 新增或修改商品
        submitForm() {
            if (!this.product.shopname) {
                this.$message.error("请输入商品名！");
                return;
            } else if (!this.product.shopimg) {
                this.$message.error("请选择照片！");
                return;
            } else if (!this.product.shopimg02) {
                this.$message.error("请选择照片！");
                return;
            } else if (!this.product.shopimg03) {
                this.$message.error("请选择照片！");
                return;
            } else if (!this.product.quantity) {
                this.$message.error("请输入商品数量！");
                return;
            } else if (!this.product.price) {
                this.$message.error("请输入商品价格！");
                return;
            } else if (!this.product.shoptext) {
                this.$message.error("请输入商品简介！");
                return;
            }else if (!this.product.fulladdress) {
                this.$message.error("请输入商品地址！");
                return;
            } else if (this.$store.state.user.wxnamder === null || this.$store.state.user.phone === null) {
                this.$message.error("请先完善个人信息(手机号，微信号)！");
                return;
            } else {
                let formData = new FormData();
                formData.append('id', this.product.id)
                formData.append('shopimg', this.product.shopimg, 'shopimg'); // 上传照片
                formData.append('shopimg02', this.product.shopimg02, 'shopimg02'); // 上传照片
                formData.append('shopimg03', this.product.shopimg03, 'shopimg03'); // 上传照片
                formData.append('shopname', this.product.shopname); // 上传其他数据
                formData.append('price', this.product.price); // 上传其他数据
                formData.append('shoptext', this.product.shoptext); // 上传其他数据
                formData.append('quantity', this.product.quantity); // 上传其他数据
                formData.append('fulladdress', this.product.fulladdress); // 上传其他数据
                formData.append('username', this.$store.state.user.username); // 上传其他数据
                formData.append('usernickname', this.$store.state.user.usernickname); // 上传其他数据
                formData.append('academy', this.$store.state.user.academy); // 上传其他数据
                formData.append('campus', this.$store.state.user.campus); // 上传其他数据
                formData.append('phone', this.$store.state.user.phone); // 上传其他数据
                formData.append('wxnamder', this.$store.state.user.wxnamder); // 上传其他数据
                $axios.post('http://localhost:9999/shopmanage', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(res => {
                    if (res.code === 200) {
                        this.$message.success("新增或修改商品成功！");
                        location.reload()
                    } else {
                        this.$message.error("新增失败！")
                    }
                })
                this.dialogVisible = false;
            }
        }
    }
}
</script>
<style>
.time {
    font-size: 13px;
    color: #999;
}

.bottom {
    margin-top: 13px;
    line-height: 12px;
}

.button {
    float: left;
}

.image {
    display: block;
    width: 100%;
    height: auto;
    object-fit: cover;
}

.square-img {
    width: 114.66px;
    height: 100px;
    overflow: hidden;
}

.bottomclearfix {

}
</style>
